<template>
  <div class="container-xl my-home-div" :style="{ '--bs-gutter-x': 0, '--my-home-div-height': '56px' }">
    <div class="row my-home-div-line ">
      <div class="col">
        <svg class="icon" aria-hidden="true">
          <use xlink:href="#icon-icon_team_Megaphone"></use>
        </svg>
        团队通知
      </div>
      <el-form :inline="true" size="default" class="col text-right">
        <el-form-item :style="{ marginBottom: 0, }">
          <el-input placeholder="请输入内容" @change="start" v-model.lazy="query._like[1]">
            <template #append>
              <el-button @click="start">
                <el-icon>
                  <Search />
                </el-icon>
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item :style="{ marginBottom: 0, marginRight: 0 }">
          <el-button type="primary" v-show="isAdmin" @click="opened">+ &nbsp; 创建通知</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="row min-height" v-if="count" :style="{ '--bs-gutter-x': 0 }">
      <div class="col" :style="{ padding: '12px' }">
        <table class="table">
          <tbody>
            <tr class=" thead">
              <td width="160">通知名称</td>
              <td scope="col">通知内容</td>
              <td width="160">通知分类</td>
              <td class="text-center" width="160">已读人数</td>
              <td class="text-center" width="160">发布时间</td>
              <td class="text-center" width="160">操作</td>
            </tr>
            <tr v-for="(v, key) in tableData" :key="key">
              <td>{{ v.name }}</td>
              <td>
                {{ v.context }}
              </td>
              <td class="text-center" v-text="v.info"></td>
              <td class="text-center">
                {{ v.usernotice.length }}
              </td>
              <td class="text-center">
                {{ formatter(v.createdAt) }}
              </td>
              <td class="text-center">
                <el-button @click="del(v.ID)" size="default">删除</el-button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <div class="row text-right" v-if="count">
      <div class="col">
        <el-pagination :hide-on-single-page="true" @current-change="handleCurrentChange"
          :page-size="Number(query._limit)" layout="prev, pager, next" :total="count"></el-pagination>
      </div>

    </div>
    <el-empty v-if="!count" image="https://cdn.hterobot.com/JOY/oj_1_1/Not%20Found%20illustration.png" />

    <el-dialog title="通知" v-model="dialogVisible" width="50%">
      <el-form :model="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="通知名称">
          <el-input placeholder="通知名称" v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="通知内容">
          <el-input type="textarea" placeholder="请填写通知内容" v-model="ruleForm.context"></el-input>
        </el-form-item>
        <el-form-item label="通知分类">
          <el-input placeholder="仅用于消息管理，消息发起者可见" v-model="ruleForm.info"></el-input>
        </el-form-item>
        <el-form-item label="跳转链接">
          <el-input placeholder="可填写题单、题目等链接用于布置作业，也可跳转外部链接" v-model="ruleForm.description"></el-input>
        </el-form-item>
        <el-form-item label="通知用户">
          <el-radio-group v-model="type">
            <el-radio label="public">所有团队成员</el-radio>
            <el-radio label="limit">指定团队成员</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="type === 'limit'" label="选择成员">
          <el-input placeholder="请输入内容" v-model="users" disabled class="input-with-select">
            <template #append>
              <el-button @click="dialogVisible2 = true">选择用户</el-button>
            </template>
          </el-input>

          <el-dialog title="请选择用户" v-model="dialogVisible2" width="900px" close-on-click-modal close-on-press-escape>
            <p>
              已选择人员：
              <!-- <span v-show="ruleForm.users">{{ ruleForm.users }}</span> -->
            </p>
            <!-- <el-button
              :type="ruleForm.users?.includes(data?.userid) ? 'success' : ''"
              @click="click(data?.user)"
            >{{ data?.user?.name }}</el-button> -->
            <el-button v-for="v in teamuser" @click="click(v.user)"
              :type="ruleForm.users?.includes(v.userid) ? 'success' : ''" :key="v.ID">{{ v.user?.name }}</el-button>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="dialogVisible2 = false">关闭</el-button>
              </span>
            </template>
          </el-dialog>
        </el-form-item>
        <div class="row">
          <div class="col text-right">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submit">确 定</el-button>
          </div>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { Search } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from "element-plus";
import { uniq } from "underscore";
import { computed, onMounted, reactive, ref, watch } from "vue";
import { useStore } from "vuex";
import { Notice } from "../../../admin/views/data";
import {
  IApinotice,
  Iobj,
  asyncteamcreateorupdatenotice,
  asyncteamdelnotice,
  asyncteamselectnotice,
} from "../../../api/index";
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { toLocaleDateString } from "../../../util/time";
import { badgeType } from "./type";

type D = {
  dialogVisible: boolean;
  activeName: string;
  sortable: "DESC" | "ASC" | undefined;
  limit: number;
  offset: number;
  like: string;
  title: string;
  ID?: number;
  context: string;
  ruleForm: IApinotice;
  rules: object;
  dialogVisible2: object;
  users: string[];
  tableData: Studycodemodel.Inotice[];
  count: number;
  order: keyof Studycodemodel.Inotice;
};
const p = defineProps<{
  data?: Studycodemodel.Iteam,
  changeteam?: (str: Studycodemodel.Iteam) => void,
  isAdmin?: 0 | 1 | 2
  user?: Studycodemodel.Iuser
  teamusers?: Studycodemodel.Iteamuser[]
  getUsers?: Function
  badge?: badgeType
}>()

const dialogVisible = ref(false)
const activeName = ref('详情')
const query = reactive<Iobj<Studycodemodel.Inotice>>({
  _sortable: 'DESC',
  _limit: 20,
  _offset: 0,
  _order: 'ID',
  _like: ['ID', '']
})

const ID = ref<number>()
const ruleForm = ref<IApinotice>(Object.assign(Notice, {}))

const rules = {}
const dialogVisible2 = ref(false)
const users = ref<string[]>([])
const tableData = ref<Studycodemodel.Inotice[]>([])
const count = ref(0)

const teamuser = computed(() => {
  return uniq(p.teamusers ? p.teamusers : [], e => {
    return e.userid
  })
})

onMounted(() => {
  start()
})

watch(query, () => {
  start()
})


async function start() {
  let { _limit, _offset, _order, _sortable, _like } = query;
  try {
    let z: [keyof Studycodemodel.Inotice, any] | undefined;
    if (_like && _like[1]) {
      z = ["name", _like[1]];
    }
    const data = await asyncteamselectnotice({
      _limit,
      _offset,
      _order,
      _sortable,
      _like: z,
      teamid: p.data?.ID,
    });
    tableData.value = data.rows;
    count.value = data.count;
  } catch (e: any) {
    ElMessage.error(e);
  }
}
function handleCurrentChange(val: number) {
  query._offset = Number(query._limit) * (val - 1);
}

function opened() {
  if (dialogVisible.value) {
    dialogVisible.value = false;
    return;
  }
  ruleForm.value = Notice
  dialogVisible.value = true;
}
function sortchange(row: any) {
  const { prop, order } = row;
  if (order == "descending") {
    query._sortable = "DESC";
  } else {
    query._sortable = "ASC";
  }
  query._order = prop;
}
function formatter(updatedAt: string) {
  return toLocaleDateString(updatedAt);
}
function del(ID: number) {
  try {
    ElMessageBox.confirm("是否删除该选项, 是否继续?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        if (p.data?.ID)
          await asyncteamdelnotice({ ID, teamid: p.data?.ID });
        ElMessage({
          type: "success",
          message: "删除成功!",
        });
        start();
      })
      .catch((e: string) => {
        if (e !== 'cancel')
          ElMessage({
            message: "删除失败" + e,
            type: "error",
          });
      });
  } catch (e: any) {
    ElMessage({
      type: "info",
      message: "已取消删除",
    });
  }
}
function click(user?: Studycodemodel.Iuser) {
  if (!ruleForm.value.users) {
    ruleForm.value.users = [];
    users.value = [];
  }
  if (ruleForm.value.users && user?.ID) {
    const i = ruleForm.value.users.indexOf(user.ID);
    if (i === -1) {
      ruleForm.value.users.push(user.ID);
      users.value.push(user.name ? user.name : "无名称");
    } else {
      ruleForm.value.users.splice(i, 1);
      users.value.splice(i, 1);
    }
  }
}

const store = useStore(Storekey)
const type = ref('public')

async function submit() {
  try {
    ruleForm.value.teamid = p.data?.ID;
    ruleForm.value.userid = store.getters.getuser.ID;
    if (type.value === "public") {
      ruleForm.value.users = undefined;
    }
    await asyncteamcreateorupdatenotice(ruleForm.value);
    ElMessage({
      message: "添加成功",
      type: "success",
    });
    start();
    dialogVisible.value = false;
  } catch (e: any) {
    ElMessage({
      message: e,
      type: "error",
    });
  }
}
</script>
<style scoped>
.thead {
  font-weight: 700;
}

table tr td {
  line-height: 30px;
}
</style>